//Initialise and Disconnect Arduino

//Digital Pin for push button bypass
#define buttonPin 13
int bypass=0; //defines whether to skip bluetooth connection or not

//Message formats for initialise and disconnect requests
#define startpacket  0x01
#define endpacket    0x04
#define datalength   0
#define checksum     0

//DO DEFINES HAVE TO BE SET AS VARIABLES SO THAT THEY CAN BE ACCESSED WHILST PROGRAM IS RUNNING?
#define initcode    0xF0 //Initialise Code
#define discocode   0xF1 //Disconnect Code
#define ackcode     0xFF //Acknowledge Code

unsigned char code[7];
unsigned short* codepoint=(unsigned short*)(code+3); //Points to shorts in data packet

//Codes to confirm configuration and start of communication (initially set to zero)
byte CONFIG=0;
byte STARTCOM=0;

void setup()
{  
  Serial.begin(115200);
  
  //Code is generic packet, changes according the communication message that is being sent
  code[1]=startpacket;
  code[2]=initcode;
  codepoint[0]=datalength;
  codepoint[1]=checksum;
  code[7]=endpacket;
  
  pinMode(buttonPin,INPUT); // set push button pin to input
}

void loop()
{
  int i;
  byte message[7];
  
  int val=digitalRead(buttonPin);
  //then according to whether val is 1 or 0 can skip steps to setup bluetooth connection or not

  if(val==1)
  {
    if(STARTCOM==0)
    {
      STARTCOM=1;
      bypass=1;
      //Send sensor configuration
    }
    
    else if(STARTCOM==1)
    {
      STARTCOM=0;
      bypass=0;
    }
    
    while(val==1)//so that can't cycle through and switch value of startcom again ie allows time to press button
    {
      val=digitalRead(buttonPin);
    } 
  }

  if(Serial.available()>6 && bypass==0)
  {
    for(i=0; i<7; i++)
        message[i]=Serial.read();
        
    if(CONFIG==0)
    {
      code[2]=initcode;
      if(memcmp(message,code,sizeof(message))==0)
      {
        CONFIG=1;//SEND SENSOR CONFIGURATION HERE!! (CALL FUNCTION?)  //is a delay necesarry to allow acknowledge to be returned in time?  
      }
    }
    
    else if(CONFIG==1)
    {
      code[2]=ackcode;
      if(memcmp(message,code,sizeof(message))==0)
      {
        CONFIG=0;
        STARTCOM=1;
      }  
    }
  }


  while(STARTCOM==1)
  {
    // THIS SECTION WILL CAL ON FUNCTION TO GATHER AND COLLATE DATA

    if(Serial.available()>6)
    {
      code[2]=discocode;
      for(i=0; i<7; i++)
        message[i]=Serial.read();

      if(memcmp(message,code,sizeof(message))==0) //could change the flow slightly by moving the ack/disc messages into if loops and doing while in seperate {}
        Serial.write(code,7);
      STARTCOM=0;
      break; //is this break necessary?
    }
  }
}
